<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<jsp:include page="header.jsp"/>
<link href="<c:url value="/css/bootstrap.min.css"/>" rel="stylesheet">
<link href="<c:url value="/css/dashboard.css"/>" rel="stylesheet">


    <title>添加导航 - 学生管理系统</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
        }


        .container {
            max-width: 1000px;
            margin: 30px auto;
            background: white;
            border-radius: 10px;
            box-shadow: 0 0 20px rgba(0, 0, 0, 0.1);
            overflow: hidden;
        }

        header {
            padding: 20px 30px;
        }

        h1 {
            font-size: 24px;
            font-weight: 600;
            display: flex;
            align-items: center;
        }

        h1 i {
            margin-right: 15px;
            font-size: 28px;
        }

        .content {
            padding: 30px;
        }

        .form-group {
            margin-bottom: 25px;
        }

        .form-group label {
            display: block;
            margin-bottom: 8px;
            font-weight: 500;
            color: #2c3e50;
        }

        .form-control {
            width: 100%;
            border: 1px solid #ddd;
            border-radius: 6px;
            font-size: 16px;
            transition: border-color 0.3s;
            box-sizing: border-box;
        }

        .form-control:focus {
            border-color: #2196f3;
            outline: none;
            box-shadow: 0 0 0 2px rgba(33, 150, 243, 0.2);
        }

        .form-hint {
            font-size: 14px;
            color: #7f8c8d;
            margin-top: 5px;
        }

        .table-container {
            border: 1px solid #e0e0e0;
            border-radius: 6px;
            overflow: hidden;
            margin-top: 10px;
        }

        .links-table {
            width: 100%;
            border-collapse: collapse;
        }

        .links-table th {
            background-color: #f5f7fa;
            padding: 12px 15px;
            text-align: left;
            font-weight: 600;
            color: #2c3e50;
            border-bottom: 1px solid #e0e0e0;
        }

        .links-table td {
            padding: 12px 15px;
            border-bottom: 1px solid #eee;
        }

        .links-table tr:last-child td {
            border-bottom: none;
        }

        .links-table tr:hover {
            background-color: #f9f9f9;
        }

        .icon-selector {
            display: grid;
            grid-template-columns: repeat(10, 1fr);
            gap: 10px;
            margin-top: 10px;
        }

        .icon-option {
            display: flex;
            flex-direction: column;
            align-items: center;
            padding: 15px 10px;
            border: 2px solid #e0e0e0;
            border-radius: 8px;
            cursor: pointer;
            transition: all 0.3s;
        }

        .icon-option:hover {
            border-color: #2196f3;
            background-color: #f0f8ff;
        }

        .icon-option.selected {
            border-color: #2196f3;
            background-color: #e3f2fd;
        }

        .icon-option i {
            font-size: 24px;
            margin-bottom: 8px;
            color: #2c3e50;
        }

        .icon-option span {
            font-size: 12px;
            color: #7f8c8d;
        }

        .buttons {
            display: flex;
            justify-content: flex-end;
            gap: 15px;
            margin-top: 30px;
            padding-top: 20px;
            border-top: 1px solid #eee;
        }

        .btn {
            padding: 12px 25px;
            border: none;
            border-radius: 6px;
            font-size: 16px;
            font-weight: 500;
            cursor: pointer;
            transition: all 0.3s;
        }

        .btn-primary {
            background: linear-gradient(135deg, #2196f3, #1976d2);
            color: white;
        }

        .btn-primary:hover {
            background: linear-gradient(135deg, #1976d2, #1565c0);
            box-shadow: 0 4px 8px rgba(33, 150, 243, 0.3);
        }

        .btn-reset {
            background-color: #f5f5f5;
            color: #555;
        }

        .btn-reset:hover {
            background-color: #e0e0e0;
        }

        .search-box {
            display: flex;
            margin-bottom: 15px;
        }

        .search-box input {
            flex: 1;
            padding: 12px 15px;
            border: 1px solid #ddd;
            border-radius: 6px 0 0 6px;
            font-size: 16px;
        }

        .search-box button {
            padding: 0 20px;
            background: #2196f3;
            color: white;
            border: none;
            border-radius: 0 6px 6px 0;
            cursor: pointer;
        }

        .required {
            color: #e53935;
        }

        .no-results {
            text-align: center;
            padding: 20px;
            color: #7f8c8d;
            font-style: italic;
        }

        @media (max-width: 768px) {
            .icon-selector {
                grid-template-columns: repeat(4, 1fr);
            }

            .container {
                margin: 15px auto;
            }

            .content {
                padding: 20px;
            }
        }

        @media (max-width: 480px) {
            .icon-selector {
                grid-template-columns: repeat(3, 1fr);
            }

            .buttons {
                flex-direction: column;
            }

            .btn {
                width: 100%;
            }
        }

        .encoding-info {
            background-color: #fff3cd;
            border: 1px solid #ffeaa7;
            border-radius: 5px;
            padding: 15px;
            margin-top: 20px;
            font-size: 14px;
        }

        .encoding-info h3 {
            color: #856404;
            margin-top: 0;
        }

        .solution-list {
            padding-left: 20px;
        }

        .solution-list li {
            margin-bottom: 8px;
        }
    </style>
<div class="container">
    <header>
        <h1><i class="fas fa-plus-circle"></i> 添加导航菜单</h1>
    </header>

    <div class="content">
        <form id="navForm">
            <div class="form-group">
                <label for="navName">导航名称 <span class="required">*</span></label>
                <input type="text" id="navName" class="form-control" placeholder="请输入导航名称" required>
                <div class="form-hint">导航菜单显示的名称，如"学生管理"、"成绩查询"等</div>
            </div>

            <div class="form-group">
                <label for="navLink">导航链接 <span class="required">*</span></label>
                <div class="search-box">
                    <input type="text" id="linkSearch" placeholder="请输入链接描述或地址...">
                    <button type="button" id="searchButton"><i class="fas fa-search"></i></button>
                </div>
                <div class="table-container">
                    <table class="links-table">
                        <thead>
                        <tr>
                            <th width="10%">选择</th>
                            <th width="10%">ID</th>
                            <th width="40%">链接地址</th>
                            <th width="40%">功能描述</th>
                        </tr>
                        </thead>
                        <tbody id="navLinksBody">
                        <!-- 这里将通过AJAX加载数据 -->
                        </tbody>
                    </table>
                </div>
                <div class="form-hint">从可用的导航链接中选择一个</div>
                <!-- 在表格后面添加分页容器 -->
                <div class="mt-3" id="paginationContainer"></div>
            </div>

            <div class="form-row">
                <!-- 新增的角色选择功能 -->
                <div class="form-group">
                    <label for="userRole"><i class="fas fa-user-tag"></i> 用户角色</label>
                    <select id="userRole" class="form-control">
                        <!-- 这里将通过AJAX加载用户数据 -->
                    </select>
                    <div class="form-hint">选择此导航菜单面向的用户角色</div>
                </div>
            </div>
            <div class="form-group">
                <label for="parentNav">父级导航</label>
                <select id="parentNav" class="form-control">
                    <option value="">无父级导航（作为顶级菜单）</option>
                    <!-- 这里将通过AJAX加载菜单数据 -->
                </select>
                <div class="form-hint">如果此导航是子菜单，请选择其父级导航</div>
            </div>

            <div class="form-group">
                <label>导航图标</label>
                <div class="icon-selector">
                    <div class="icon-option" data-icon="fas fa-user-graduate">
                        <i class="fas fa-user-graduate"></i>
                        <span>学生</span>
                    </div>
                    <div class="icon-option" data-icon="fas fa-chart-bar">
                        <i class="fas fa-chart-bar"></i>
                        <span>统计</span>
                    </div>
                    <div class="icon-option" data-icon="fas fa-book">
                        <i class="fas fa-book"></i>
                        <span>课程</span>
                    </div>
                    <div class="icon-option" data-icon="fas fa-home">
                        <i class="fas fa-home"></i>
                        <span>宿舍</span>
                    </div>
                    <div class="icon-option" data-icon="fas fa-clipboard-list">
                        <i class="fas fa-clipboard-list"></i>
                        <span>考勤</span>
                    </div>
                    <div class="icon-option" data-icon="fas fa-cog">
                        <i class="fas fa-cog"></i>
                        <span>设置</span>
                    </div>
                    <div class="icon-option" data-icon="fas fa-graduation-cap">
                        <i class="fas fa-graduation-cap"></i>
                        <span>毕业</span>
                    </div>
                    <div class="icon-option" data-icon="fas fa-calendar-alt">
                        <i class="fas fa-calendar-alt"></i>
                        <span>日程</span>
                    </div>
                    <div class="icon-option" data-icon="fas fa-money-bill-wave">
                        <i class="fas fa-money-bill-wave"></i>
                        <span>缴费</span>
                    </div>
                    <div class="icon-option" data-icon="fas fa-comments">
                        <i class="fas fa-comments"></i>
                        <span>讨论</span>
                    </div>
                    <div class="icon-option" data-icon="fas fa-award">
                        <i class="fas fa-award"></i>
                        <span>成绩</span>
                    </div>
                    <div class="icon-option" data-icon="fas fa-users">
                        <i class="fas fa-users"></i>
                        <span>班级</span>
                    </div>
                    <div class="icon-option" data-icon="fas fa-history">
                        <i class="fas fa-history"></i>
                        <span>历史</span>
                    </div>
                    <div class="icon-option" data-icon="fas fa-chart-line">
                        <i class="fas fa-chart-line"></i>
                        <span>进度</span>
                    </div>
                    <div class="icon-option" data-icon="fas fa-bell">
                        <i class="fas fa-bell"></i>
                        <span>通知</span>
                    </div>
                    <div class="icon-option" data-icon="fas fa-book-open">
                        <i class="fas fa-book-open"></i>
                        <span>教材</span>
                    </div>
                    <div class="icon-option" data-icon="fas fa-id-card">
                        <i class="fas fa-id-card"></i>
                        <span>档案</span>
                    </div>
                    <div class="icon-option" data-icon="fas fa-tasks">
                        <i class="fas fa-tasks"></i>
                        <span>作业</span>
                    </div>
                    <div class="icon-option" data-icon="fas fa-file-alt">
                        <i class="fas fa-file-alt"></i>
                        <span>报告</span>
                    </div>
                    <div class="icon-option" data-icon="fas fa-question-circle">
                        <i class="fas fa-question-circle"></i>
                        <span>帮助</span>
                    </div>
                </div>
                <input type="hidden" id="selectedIcon" name="navIcon">
                <div class="form-hint">选择导航菜单前显示的图标</div>
            </div>

            <div class="buttons">
                <button type="button" class="btn btn-reset">重置</button>
                <button type="submit" class="btn btn-primary">提交</button>
            </div>
        </form>
    </div>
</div>
<div class="modal fade" id="autoCloseModal" data-bs-autohide="true" data-bs-delay="3000" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-body">
                添加成功，请等待页面自动关闭...
            </div>
        </div>
    </div>
</div>
<script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.11.6/dist/umd/popper.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.min.js"></script>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
    $(document).ready(function () {
        // 初始化搜索功能
        initSearchFunctionality();

        // 加载导航数据
        loadNavData();

        // 图标选择功能
        $('.icon-option').click(function () {
            $('.icon-option').removeClass('selected');
            $(this).addClass('selected');
            $('#selectedIcon').val($(this).data('icon'));
        });

            // 在实际应用中，这里应该发送AJAX请求或提交表单到服务器
           /* console.log('导航名称:', navName);
            console.log('导航链接:', navLink.val());
            console.log('父级导航:', parentNav);
            console.log('导航图标:', navIcon);
            //打印被选中的角色id
            console.log('被选中的角色id:', selectedRoleId);
            console.log('导航链接Path:', navLinkPath);*/
            //ajax发送请求到后端
            // 表单提交处理

            $('#navForm').on('submit', function(e) {
                e.preventDefault();

                const navName = $('#navName').val();
                const navLinkRadio = $('input[name="navLink"]:checked');

                if (!navLinkRadio.length) {
                    alert('请选择导航链接');
                    return;
                }
                //获取被选中的角色id
                const selectedRoleId = parseInt($('#userRole').val());//获取被选中的角色id
                const navLinkId = parseInt(navLinkRadio.val());
                //获取导航链接Path
                const navLinkPathElem = navLinkRadio.closest('tr').find('td:eq(2)');
                const navLinkPath = navLinkPathElem.text(); // 获取文本内容

                const parentNavElem = $('#parentNav');//获取父级导航的id

                const parentNav = parentNavElem.val() ? parseInt(parentNavElem.val()) : 0;//如果为空，则设为0
                const navIcon = $('#selectedIcon').val() || "fas fa-link";//如果没有选择图标，则使用默认图标

                // 确保角色ID有值 - 这里需要根据您的页面结构修改


                if (!navName) {
                    alert('请输入导航名称');
                    return;
                }

                // 打印发送的数据以便调试
                // console.log("发送的数据:", {
                //     navName: navName,
                //     navLink: navLinkId,
                //     parentNav: parentNav,
                //     navIcon: navIcon,
                //     roleId: selectedRoleId,
                //     navLinkPath: navLinkPath
                // });

                // 发送AJAX请求
                $.ajax({
                    url: 'addnavigation',
                    type: 'POST',
                    contentType: 'application/json',
                    data: JSON.stringify({
                        navName: navName,
                        navLink: navLinkId,
                        parentNav: parentNav,
                        navIcon: navIcon,
                        roleId: selectedRoleId, // 确保这个参数存在
                        navLinkPath: navLinkPath
                    }),
                    success: function(response) {
                        console.log("服务器响应:", response);
                        if (response.success) {
                            modal.show();
                            resetForm();
                        } else {
                            modal.show();
                        }
                    },
                    error: function(xhr, status, error) {
                        console.error("请求错误:", error);
                        alert('请求失败: ' + error);
                    }
                });
            });


        });

        // 重置按钮
        $('.btn-reset').click(function () {
            resetForm();
        });

        // 搜索按钮点击事件
        $('#searchButton').click(function () {
            performSearch();
        });

        // 搜索框回车事件
        $('#linkSearch').keypress(function (e) {
            if (e.which === 13) {
                e.preventDefault();
                performSearch();
            }
    });

    // 初始化搜索功能
    function initSearchFunctionality() {
        // 搜索框输入事件
        $('#linkSearch').on('input', function () {
            performSearch();
        });
    }

    // 执行搜索
    function performSearch() {
        const searchTerm = $('#linkSearch').val().toLowerCase().trim();
        const $rows = $('#navLinksBody tr');
        let hasResults = false;

        $rows.each(function () {
            const link = $(this).find('td:eq(2)').text().toLowerCase();
            const desc = $(this).find('td:eq(3)').text().toLowerCase();

            if (link.includes(searchTerm) || desc.includes(searchTerm)) {
                $(this).show();
                hasResults = true;
            } else {
                $(this).hide();
            }
        });

        // 显示无结果提示
        if (!hasResults) {
            if (!$('.no-results').length) {
                $('.links-table').after('<div class="no-results">没有找到匹配的链接</div>');
            }
        } else {
            $('.no-results').remove();
        }
    }

    // 加载导航数据（NavLink和menus）
    function loadNavData() {
        $.ajax({
            url: 'addnavigation',
            type: 'POST',
            contentType: 'application/json',
            success: function (data) {
                // 如果data是JSON字符串，需要先解析
                const jsonData = typeof data === 'string' ? JSON.parse(data) : data;

                // 检查数据结构，可能是 {NavLink: [...], menus: [...]} 格式
                const navLinks = jsonData.NavLink || jsonData;
                const menus = jsonData.menus || [];
                const roles = jsonData.roles || [];
                //渲染角色下拉菜单
                renderRoleMenu(roles);
                // 渲染导航链接表格
                renderNavLinks(navLinks);

                // 渲染父级导航下拉菜单
                renderParentNavMenu(menus);

                // 重新初始化搜索功能，确保对新加载的行有效
                initSearchFunctionality();

                // 如果有搜索词，重新执行搜索
                if ($('#linkSearch').val()) {
                    performSearch();
                }
            },
            error: function () {
                alert('加载导航数据失败，请刷新页面重试');
            }
        });
    }

    // 渲染角色下拉菜单
    function renderRoleMenu(roles) {
        const userRole = $('#userRole');
        userRole.html('<option value="">请选择角色</option>');

        // 检查roles是否为有效数组
        if (!Array.isArray(roles) || roles.length === 0) {
            userRole.append('<option value="">无可用角色</option>');
            return;
        }
        roles.forEach(function (role) {
            // 添加null检查和属性存在检查
            if (role && role.id !== undefined && role.roleName !== undefined && role.id !== 3) {
                // 使用更安全的HTML转义
                const optionValue = $('<div>').text(role.id).html();
                const optionText = $('<div>').text(role.roleName).html();
                userRole.append('<option value="' + optionValue + '">' + optionText + '</option>');
            }
        });
        // 如果没有添加任何选项，显示提示
        if (userRole.find('option').length === 1) {
            userRole.append('<option value="">无可选角色</option>');
        }

    }

    // 渲染导航链接表格
        // 全局变量
        let currentPage = 1;
        const itemsPerPage = 5;
        let allNavLinks = [];

        function renderNavLinks(navLinks) {
            // 保存所有数据
            allNavLinks = navLinks || [];

            if (allNavLinks.length === 0) {
                $('#navLinksBody').html('<tr><td colspan="4" style="text-align: center; padding: 20px;">暂无导航链接数据</td></tr>');
                $('#paginationContainer').empty();
                return;
            }

            // 计算总页数
            const totalPages = Math.ceil(allNavLinks.length / itemsPerPage);

            // 渲染当前页数据
            renderCurrentPageData();

            // 渲染分页控件
            renderPagination(totalPages);
        }

        function renderCurrentPageData() {
            const startIndex = (currentPage - 1) * itemsPerPage;
            const endIndex = Math.min(startIndex + itemsPerPage, allNavLinks.length);
            const currentPageData = allNavLinks.slice(startIndex, endIndex);

            const tableContent = currentPageData.map(function (item) {
                return '<tr>' +
                    '<td><input type="radio" name="navLink" value="' + item.id + '"></td>' +
                    '<td>' + item.id + '</td>' +
                    '<td>' + (item.path || '') + '</td>' +
                    '<td>' + (item.description || '') + '</td>' +
                    '</tr>';
            }).join('');

            $('#navLinksBody').html(tableContent);
        }

        function renderPagination(totalPages) {
            let paginationHtml = '<nav aria-label="Page navigation">' +
                '<ul class="pagination pagination-sm justify-content-center">';

            // 上一页按钮
            paginationHtml += '<li class="page-item ' + (currentPage === 1 ? 'disabled' : '') + '">' +
                '<a class="page-link" href="#" data-page="prev" aria-label="Previous">' +
                '<span aria-hidden="true">&laquo;</span>' +
                '</a></li>';

            // 页码按钮
            for (let i = 1; i <= totalPages; i++) {
                paginationHtml += '<li class="page-item ' + (currentPage === i ? 'active' : '') + '">' +
                    '<a class="page-link" href="#" data-page="' + i + '">' + i + '</a></li>';
            }

            // 下一页按钮
            paginationHtml += '<li class="page-item ' + (currentPage === totalPages ? 'disabled' : '') + '">' +
                '<a class="page-link" href="#" data-page="next" aria-label="Next">' +
                '<span aria-hidden="true">&raquo;</span>' +
                '</a></li>';

            paginationHtml += '</ul></nav>';

            $('#paginationContainer').html(paginationHtml);
        }

        // 分页点击事件处理
        $(document).on('click', '.page-link', function(e) {
            e.preventDefault();

            const pageAction = $(this).data('page');
            const totalPages = Math.ceil(allNavLinks.length / itemsPerPage);

            if (pageAction === 'prev' && currentPage > 1) {
                currentPage--;
            } else if (pageAction === 'next' && currentPage < totalPages) {
                currentPage++;
            } else if (typeof pageAction === 'number') {
                currentPage = pageAction;
            }

            renderCurrentPageData();
            renderPagination(totalPages);
        });

    // 渲染父级导航下拉菜单
    function renderParentNavMenu(menus) {
        const $parentNav = $('#parentNav');
        // 清空现有选项（保留第一个"无父级导航"选项）
        $parentNav.find('option:not(:first)').remove();

        if (!menus || menus.length === 0) {
            return;
        }

        // 添加菜单选项
        menus.forEach(function (menu) {
            $parentNav.append('<option value="' + menu.id + '">' + (menu.name || '未命名菜单') + '</option>');
        });
    }

    // 重置表单
    function resetForm() {
        $('#navForm')[0].reset();
        $('.icon-option').removeClass('selected');
        $('#selectedIcon').val('');
        $('#linkSearch').val('');
        $('#userRole').val('');

        // 显示所有行
        $('#navLinksBody tr').show();
        $('.no-results').remove();
    }
</script>
<jsp:include page="footer.jsp"/>
